# -*- coding: utf-8 -*-..,
##############################################################################
#
#    @author: PhongND
#    Copyright (C) 2014 Crea8s (http://www.crea8s.com) All Rights Reserved.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import tools
from itertools import count
# ===== =====
# import pytz
# import tzlocal
# from tzlocal import get_localzone # $ pip install tzlocal
# ===== =====
# from xmlrpclib import ServerProxy, Error

# -*- coding: utf-8 -*-

from openerp.modules.registry import RegistryManager

class Website(osv.Model):
    """
    website > store > store view.
    """
    _name = "crea8s.magento.website"    
    _description = 'crea8s.magento.website...'
    _columns = {
                
        # identify fields below
        'magento_id': fields.integer('Magento ID', readonly=True,),
        'magento_root_category_id': fields.integer(
            'Magento Root Category ID',
        ),

        
        # other fields
        'name': fields.char('Name', size=100),
        'code': fields.char('Code', size=50),
        'instance': fields.many2one('crea8s.magento.instance', 'Instance', required=True),
        
        'company': fields.related('instance', 'company', type='many2one', relation='res.company', string='Company'),
        'default_product_uom': fields.many2one('product.uom', 'Default Product UOM'),
#         'magento_cat_id': fields.char('Magento Root Category ID'),
        'stores': fields.one2many('crea8s.magento.store', 'website', 'Stores'),
                        
    }
    _default = {
        'magento_root_category_id': lambda *a: 1,
                }
    
    def find_or_create(self, cr, uid, instance_id, values, context):
        
        """
        Create magento website
        :author phongnd
        :created_date: 20140909
        :param none: nothing
               Format :
                   {<attribute>:{<operator>:<value>}}
               Example :
                   {'website_id':{'=':'1'}}
        :return: none
        """
        
        website_ids = self.search(
            cr, uid, [
                ('instance', '=', instance_id),
                ('magento_id', '=', int (values['website_id'])) #,124) # 
            ], context=context
        )
        
        arrValues_ORM = {
                        'name': values['name'], #'web 01', # 
                        'code': values['code'], #'web01',# 
                        'instance': instance_id, # instance_id, # 
                        'magento_id':  values['website_id'], #123,# 
                    }
#         website_ids = None
        if (website_ids != None): # if website_ids:
            if (len(website_ids) > 0):
                print '+ return website_ids[0]= ' + str(website_ids) + '; len=' + str(len(website_ids))
                self.write(cr, uid, website_ids, arrValues_ORM, context=context)
                return website_ids[0]

        print '+ self.create(....); values=' + str(values)
        #values={'code': 'web02', 'name': 'web 02', 'website_id': '2', 'is_default': '0', 'sort_order': '0', 'default_group_id': '2'}
        iID = self.create(cr, uid, arrValues_ORM, context=context)
        print '+ self.ID= ' + str(iID)
        return iID
    
    def unlink(self, cr, uid, ids, context=None):
        arrORMs = self.browse(cr, uid, ids, context=context)
        unlink_ids = []
        boRemove = True
        for item in arrORMs:
            if item.stores:
#                 if count(item.stores) > 0:
#                 if count(item.stores, lambda p: p.id) > 0:  # nonono
                if  sum(p.id for p in item.stores) > 0:
                    boRemove = False
            if boRemove == True:
                unlink_ids.append(item.id)
    
        if boRemove == False:
            raise osv.except_osv(_('Invalid Action!'), _('Can not remove any items, because there\'re its childs.'))
        else:
            return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
     
     
    def get_default_uom(self, cursor, user, context):
        """
        Get default product uom for website.

        :param cursor: Database cursor
        :param user: ID of current user
        :param context: Application context
        :return: UOM browse record
        """
        website = self.browse(
            cursor, user, context['magento_website'], context=context
        )

        if not website.default_product_uom:
            raise osv.except_osv(
                _('UOM not found!'),
                _('Please define Default Product UOM for website %s') %
                website.name,
            )

        return website.default_product_uom   
        

class Store(osv.Model):
    _name = "crea8s.magento.store"
    _description = 'crea8s.magento.store....'
    _columns = {
        # identify fields below
        'magento_id': fields.integer('Magento ID', readonly=True,),
        'website': fields.many2one('crea8s.magento.website', 'Website'),
        # other fields
        'views': fields.one2many('crea8s.magento.view', 'store', 'Store Views'),                
        'name': fields.char('Name..', size=100),
        'instance': fields.related('website', 'instance', type='many2one', relation='crea8s.magento.instance', string='Instance'),
        'company': fields.related('website', 'company', type='many2one', relation='res.company', string='Company'),        
        'shop': fields.many2one(
            'sale.shop', 'Sales Shop',
            help="Imported sales for this store will go into this shop",
        ),
                
        # Root Category  ?
    }
    
    _sql_constraints = [(
        'magento_id_website_unique', 'unique(magento_id, website)',
        'A store must be unique in a website'
    )]
    
    def find_or_create(self, cr, uid, website_id, values, context):
        
        """
        Create magento stores
        :author phongnd
        :created_date: 20140912
        :param none: nothing
        :return: none
        """
        
        print 'Store.find_or_create() ' + str(values) 
        # {'default_store_id': '1', 'group_id': '1', 'website_id': '1', 'name': 'Main Website Store', 'root_category_id': '2'}
        # {'default_store_id': '4', 'group_id': '2', 'website_id': '2', 'name': 'web_store02.1', 'root_category_id': '2'}

        
        store_ids = self.search(
            cr, uid, [
                ('website', '=', website_id),
                ('magento_id', '=', int (values['group_id'])) #,124) # 
            ], context=context
        )
        # create values for updating, creating
        arrValues_ORM = {                         
                'name': values['name'], #'web 01', # 
                'website': website_id, # instance_id, # 
                'magento_id':  values['group_id'], #123,# 
                         }
#         store_ids = None
        if (store_ids != None): # if store_ids:
            if (len(store_ids) > 0):
                self.write(cr, uid, store_ids, arrValues_ORM, context=context)
                print '+ return store_ids[0]= ' + str(store_ids) + '; len=' + str(len(store_ids))
                return store_ids[0]
 
#         print '+ self.create(....); values=' + str(values) 
        iID = self.create(cr, uid, arrValues_ORM, context=context)
        print '+ self.ID= ' + str(iID)
        return iID
    
    def unlink(self, cr, uid, ids, context=None):
        arrORMs = self.browse(cr, uid, ids, context=context)
        unlink_ids = []
        boRemove = True
        for item in arrORMs:
            if item.views:
#                 if count(item.stores) > 0:
#                 if count(item.stores, lambda p: p.id) > 0:  # nonono
                if  sum(p.id for p in item.views) > 0:
                    boRemove = False
            if boRemove == True:
                unlink_ids.append(item.id)
    
        if boRemove == False:
            raise osv.except_osv(_('Invalid Action!'), _('Can not remove any items, because there\'re its childs.'))
        else:
            return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
    
    
class View(osv.Model):
    _name = "crea8s.magento.view"
    _description = 'crea8s.magento.view....'
    _columns = {
        'name': fields.char('Name..', size=100),
        'code': fields.char('Code', size=50),
        'status': fields.boolean('Status'),
        # identify fields below
        'magento_id': fields.integer('Magento ID', readonly=True,),
        'store': fields.many2one('crea8s.magento.store', 'Store'),
        'instance': fields.related('store', 'instance', type='many2one', relation='crea8s.magento.instance', string='Instance'),
        }
    
    def find_or_create(self, cr, uid, store_id, values, context):
        
        """
        Create magento views
        :author phongnd
        :created_date: 20140912
        :param none: nothing
        :return: none
        """
        
        print 'View.find_or_create() ' + str(values) 
        # {'code': 'view_02_01_01', 'store_id': '5', 'website_id': '2', 'is_active': '1', 'sort_order': '0', 'group_id': '2', 'name': 'View 02 01 01'}
        # {'code': 'view_02_01_02', 'store_id': '4', 'website_id': '2', 'is_active': '1', 'sort_order': '0', 'group_id': '2', 'name': 'View 02 01 02'}
         
        view_ids = self.search(
            cr, uid, [
                ('store', '=', store_id),
                ('magento_id', '=', int (values['store_id'])) #,124) # 
            ], context=context
        )
        # create values for updating, creating
        arrValues_ORM = {                         
                'name': values['name'], #'web 01', # 
                'code': values['code'], #'web 01', # 
                'store': store_id, # instance_id, # 
                'magento_id':  values['store_id'], #123,# 
                         }
        
#         view_ids = None
        if (view_ids != None): #nonono,  if view_ids:
            if (len(view_ids) > 0):
                self.write(cr, uid, view_ids, arrValues_ORM, context=context)
                print '+ return view_ids[0]= ' + str(view_ids) + '; len=' + str(len(view_ids))
                return view_ids[0]
 
#         print '+ self.create(....); values=' + str(values) 
        iID = self.create(cr, uid, arrValues_ORM, context=context)
        print '+ self.ID= ' + str(iID)
        return iID
    
    
    